package com.wfcm.service.impl;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.wfcm.entity.*;
import com.wfcm.jedis.JedisDao;
import com.wfcm.jedis.JedisResult;
import com.wfcm.service.*;
import com.wfcm.utils.ISsoLoginHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.wfcm.dao.WfIndexTypeDao;

import javax.servlet.http.HttpServletRequest;


@Service("wfIndexTypeService")
public class WfIndexTypeServiceImpl implements WfIndexTypeService {
	@Autowired
	private WfIndexTypeDao wfIndexTypeDao;
	@Autowired
	private WfIndexRecommendServiceImpl indexRecommendService;
	@Autowired
	private WfCourseInfoService courseInfoService;
	@Autowired
	private WfChapterRecordService chapterRecordService;
	@Autowired
	private JedisDao jedisDao;
	@Autowired
	private WfAdInfoService wfAdInfoService;
	@Autowired
	private WfActivityNewsService wfActivityNewsService;
	@Autowired
	private WfNewMessageService newMessageService;
	@Autowired
	private WfIconService iconService;

	@Value("${activityNews}")
	private String activityNews;
	@Value("${Complete}")
	private String Complete;

	@Override
	public WfIndexTypeEntity queryObject(Integer indextypecode){
		return wfIndexTypeDao.queryObject(indextypecode);
	}
	
	@Override
	public List<WfIndexTypeEntity> queryList(Map<String, Object> map){
		return wfIndexTypeDao.queryList(map);
	}

	@Override
	public int queryTotal(Map<String, Object> map){
		return wfIndexTypeDao.queryTotal(map);
	}
	
	@Override
	public void save(WfIndexTypeEntity wfIndexType){
		wfIndexTypeDao.save(wfIndexType);
	}
	
	@Override
	public void update(WfIndexTypeEntity wfIndexType){
		wfIndexTypeDao.update(wfIndexType);
	}
	
	@Override
	public void delete(Integer indextypecode){
		wfIndexTypeDao.delete(indextypecode);
	}
	
	@Override
	public void deleteBatch(Integer[] indextypecodes){
		wfIndexTypeDao.deleteBatch(indextypecodes);
	}

	@Override
	public int delIndexType() {
		// 1. 访问redis
		int i = -1;
		try{
			i = this.jedisDao.del(this.activityNews);
		}catch(Exception e){
			e.printStackTrace();
		}
		// 5. 返回结果
		return i;
	}

	private Map getIndexMap(int indexTypeCode, int num, String typeName){
		Map<String,Object>  map = new HashMap<String,Object>();
		//10,免费课程  ； 11，精品课程； 12，超值课程包；22,数学分级课  ;23语文分级课； 24，音频推荐； 25，今日推荐
		map.put("indexTypeCode", indexTypeCode);
		int total = indexRecommendService.queryTotal(map);
		map.put("num", num);//首页分类展示数据的条数
		List <WfIndexRecommendEntity> indexList = new ArrayList<WfIndexRecommendEntity>();
		List <WfIndexRecommendEntity> resultList = new ArrayList<WfIndexRecommendEntity>();
		indexList = indexRecommendService.queryIndexList(map);
		for(int i=0 ; i<indexList.size(); i++) {
			WfIndexRecommendEntity indexRecommendEntity = indexList.get(i);
			if(1 == indexRecommendEntity.getBuytype()) {//按课程购买
				map.put("courseId",indexRecommendEntity.getCourseid() );
				//查出首页推荐类别 -- 查出对应的课程 -- 查出对应的讲师
				WfIndexRecommendEntity courseInfo = indexRecommendService.queryCourseInfo(map);
				courseInfo.getCourseInfoEntity().setLabel(courseInfoService.queryCourseLabel(1, courseInfo.getCourseid()));
				resultList.add(courseInfo);
			}else if(2 == indexRecommendEntity.getBuytype()){//按章节购买
				map.put("chapterId",indexRecommendEntity.getChapterid() );
				//查出首页推荐类别  -- 查出对应的章节-- 查出对应的课程  -- 查出对应的讲师
				WfIndexRecommendEntity courseChapter = indexRecommendService.queryCourseChapter(map);
				//查询播放次数
				WfChapterRecordEntity chapterRecord = chapterRecordService.queryObject(indexRecommendEntity.getChapterid() );
				if(null != chapterRecord) {
					courseChapter.setSalecount(chapterRecord.getNumber());
				}
				courseChapter.getCourseChapterEntity().setLabel(courseInfoService.queryCourseLabel(2, courseChapter.getChapterid()));
				resultList.add(courseChapter);

			}else if(3 == indexRecommendEntity.getBuytype()){//按课程包购买
				map.put("cardId",indexRecommendEntity.getCardid() );
				//查出首页推荐类别 -- 查出对应的课程包
				WfIndexRecommendEntity vipCard = indexRecommendService.querySimpleVipCard(map);
				vipCard.getVipCardEntity().setLabel(courseInfoService.queryCourseLabel(3, vipCard.getCardid()));
				resultList.add(vipCard);
			}
		}
		Map<String,Object>  resultMap = new HashMap<String,Object>();
		resultMap.put("resultList", resultList);
		resultMap.put("total",total);
		resultMap.put("typeName",typeName);
		return resultMap;
	}

	/*@Override
	public IndexTypeResult jedisList() {
		// 1. 访问redis
		try{
			String redisResult = this.jedisDao.hget(this.activityNews, "1");
			// 2. 判断访问redis结果
			if(redisResult != null && redisResult.trim().length() > 0){
				// 将JSON格式的JedisResult字符串.转化成JedisResult对象. 其中data属性类型为List集合.集合泛型为Map
				return IndexTypeResult.formatToList(redisResult, Map.class);
				// 将JSON格式的JedisResult字符串.转化成JedisResult对象. 其中data属性类型为引用类型,data具体类型是Object
				// JedisResult.formatToPojo(jsonString, Object.class);
			}
		}catch(Exception e){
			e.printStackTrace();
		}

		// 3. 访问数据库
		List<WfIndexTypeEntity>  indexTypeList = wfIndexTypeDao.queryList(null);
		List<Map> resultList = new ArrayList<>();
		for (int i = 0; i < indexTypeList.size(); i++) {
			WfIndexTypeEntity indexType = indexTypeList.get(i);
			int num = 0;
			if(indexType.getIndexRecommend().getDisplaytype()!=2) {
				num=4;
			}else { num=1; }
			Map m = getIndexMap(indexType.getIndextypecode(),num,indexType.getIndextypename());
			resultList.add(m);
		}
		IndexTypeResult resultObject = IndexTypeResult.ok(resultList);

		// 4. 增加redis缓存
		try{
			ObjectMapper mapper = new ObjectMapper();
			this.jedisDao.hset(this.activityNews, "1",
					mapper.writeValueAsString(resultObject));
		}catch(Exception e){
			e.printStackTrace();
		}

		// 5. 返回结果
		return resultObject;
	}*/

	@Override
	public JedisResult indexComplete(HttpServletRequest req) {
		// 1. 访问redis
		try{
			String redisResult = this.jedisDao.hget(this.activityNews, this.Complete);
			// 2. 判断访问redis结果
			if(redisResult != null && redisResult.trim().length() > 0){
				// 将JSON格式的JedisResult字符串.转化成JedisResult对象. 其中data属性类型为List集合.集合泛型为Map
				return JedisResult.formatToPojo(redisResult, Map.class);
				// 将JSON格式的JedisResult字符串.转化成JedisResult对象. 其中data属性类型为引用类型,data具体类型是Object
				// JedisResult.formatToPojo(jsonString, Object.class);
			}
		}catch(Exception e){
			e.printStackTrace();
		}

		// 3. 访问数据库
		List<WfIndexTypeEntity>  indexTypeList = wfIndexTypeDao.queryList(null);
		List<Map> resultList = new ArrayList<>();
		for (int i = 0; i < indexTypeList.size(); i++) {
			WfIndexTypeEntity indexType = indexTypeList.get(i);
			int num = 0;
			if(indexType.getIndexRecommend().getDisplaytype()!=2) {
				num=4;
			}else { num=1; }
			Map m = getIndexMap(indexType.getIndextypecode(),num,indexType.getIndextypename());
			resultList.add(m);
		}
        Map<String,Object> r = new HashMap<String,Object>();
		List<WfAdInfoEntity> adList = wfAdInfoService.queryList(null);
		try {
			// 展示控制 1 (ios) 2 (android) 3 (h5)
			Map<Integer, List<Integer>> map = wfAdInfoService.displayControl();
			String userAgent = req.getHeader("user-agent");
			if (userAgent.contains("iOS") && map.get(1).size() > 0) {
				for (int i = 0; i < adList.size(); i++) {
					if (map.get(1).contains(adList.get(i).getId())) {
						adList.remove(i);
					}
				}
			} else if (userAgent.contains("okhttp") && map.get(2).size() > 0) {
				for (int i = 0; i < adList.size(); i++) {
					if (map.get(2).contains(adList.get(i).getId())) {
						adList.remove(i);
					}
				}
			} else if (map.get(3).size() > 0) {
				for (int i = 0; i < adList.size(); i++) {
					if (map.get(3).contains(adList.get(i).getId())) {
						adList.remove(i);
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		List<WfActivityNewsEntity> newsList = wfActivityNewsService.queryList(null);
		List<WfIconEntity> iconList = iconService.queryList(null);

		Integer userId = ISsoLoginHelper.confirm(req);
		if(userId != null && 0 != newMessageService.newFlag(userId)){
			r.put("newFlag",1);//有新消息
		}else {
			r.put("newFlag",0);
		}

		r.put("adList",adList);
		r.put("iconList",iconList);
		r.put("newsList",newsList);
		r.put("resultList",resultList);

		JedisResult resultObject = JedisResult.ok(r);

		// 4. 增加redis缓存
		try{
			ObjectMapper mapper = new ObjectMapper();
			this.jedisDao.hset(this.activityNews, this.Complete,
					mapper.writeValueAsString(resultObject));
		}catch(Exception e){
			e.printStackTrace();
		}

		// 5. 返回结果
		return resultObject;
	}

}
